﻿#include"mystdio.h"
#include<sys/types.h>
#include<string.h>
#include<sys/stat.h>
#include<fcntl.h>

mFILE* mfopen(const char* path, const char* mode)
{
    int tmp_fd = -1;
    if (strcmp(mode, 'r') == 0)
    {
        tmp_fd = open(path, O_RDONLY);
    }
    else if (strcmp(mode, 'w'))
    {
        tmp_fd = open(path, O_CREAT | O_WRONLY | O_TRUNC, 0666);
    }
    else if (strcmp(mode, 'a'))
    {
        tmp_fd = open(path, O_CREAT | O_WRONLY | O_APPEND, 0666);
    }

    if (tmp_fd == -1)
        return NULL;

    mFILE* ret = (mFILE*)malloc(sizeof(mFILE));
    ret->_fd = tmp_fd;
    ret->size = MAX_SIZE;
    ret->_flash= FLUSH_LINE;

    return ret;
}

void mfflush(mFILE* stream)
{
    if (stream->size > 0)
    {
        // 写到内核⽂件的⽂件缓冲区中!
        write(stream->_fd, stream->buffer, stream->size);
        // 刷新到外设
        fsync(stream->_fd);
        stream->size = 0;
    }
}


int mfwrite(const void* ptr, int num, mFILE* stream)
{
    int ret = 0;
    //ptr是文件写入的缓冲区
    memcpy(ptr, stream->buffer + stream ->size, size(stream->buffer));
    ret = write(stream->_fd, ptr, num);

    if (stream->_flash == FLUSH_LINE && stream->size > 0 && stream->buffer[stream->size - 1] == '\n')
    {
        mfflush(stream);
    }

    return ret;
}

void mfclose(mFILE* stream)
{
    close(stream->_fd);
}
